package com.jfinal.plugin.activerecord;

import java.util.Map;

public class Sql {
	private static ThreadLocal<SqlPro> LocalSql = new ThreadLocal<SqlPro>();

	static SqlPro sql() {
		SqlPro sqlPro = LocalSql.get();
		if (sqlPro == null) {
			sqlPro = new SqlPro();
		}
		return sqlPro;
	}

	public static SqlPro ues(String configName) {
		return new SqlPro(configName);
	}

	public SqlPro setAlias(String alias) {
		return sql().setAlias(alias);
	}

	public SqlPro where(String namedWhereSql, Map<String, Object> paraMap) {
		return sql().where(namedWhereSql, paraMap);
	}

	public SqlPro where(String whereSql, Object... paras) {
		return sql().where(whereSql, paras);
	}

	/*-----------------------------  buildUpdateSql begin ------------------------------*/
	public <M extends Model<?>> SqlPro buildUpdateSql(Model<M> model) {
		try {
			return sql().buildUpdateSql(model);
		} finally {
			LocalSql.set(null);
		}
	}

	public SqlPro buildUpdateSql(String tableName, Record record) {
		try {
			return sql().buildUpdateSql(tableName, record);
		} finally {
			LocalSql.set(null);
		}
	}

	public SqlPro buildUpdateSql(String tableName, Map<String, Object> attrs) {
		try {
			return sql().buildSaveSql(tableName, attrs);
		} finally {
			LocalSql.set(null);
		}
	}

	/*---------------------------- buildFindSql begin ----------------------------*/
	public SqlPro buildFindSql(String tableName) {
		try {
			return sql().buildFindSql(tableName);
		} finally {
			LocalSql.set(null);
		}
	}

	public SqlPro buildFindSql(String tableName, String columns) {
		try {
			return sql().buildFindSql(tableName, columns);
		} finally {
			LocalSql.set(null);
		}
	}

	/*-----------------------------  buildDeleteSql begin ------------------------------*/
	public SqlPro buildDeleteSql(String tableName) {
		try {
			return sql().buildDeleteSql(tableName);
		} finally {
			LocalSql.set(null);
		}
	}

	/*-----------------------------  buildSaveSql begin ------------------------------*/
	public SqlPro buildSaveSql(String tableName, Map<String, Object> attrs) {
		try {
			return sql().buildSaveSql(tableName, attrs);
		} finally {
			LocalSql.set(null);
		}
	}
}
